#include "spk_camera.h"
#include "config.h"
#include "video.h"
#include "video_v4l2.h"
#include "video_mpp.h"
#include "video_osd.h"

#define LOG_TAG "video"
#define LOG_LVL LOG_LVL_INFO
#include "spk_ulog.h"

cls_video::cls_video(cls_spkcam *p_app)
{
    app = p_app;
    cfg_src = app->cfg_src;
    cfg_cur = app->cfg_cur;

    video_running = true;
    init_images();
}

cls_video::~cls_video()
{
    video_loop_stop();

    app = nullptr;
    cfg_src = nullptr;
    cfg_cur = nullptr;
    video_running = false;
    free_images();
}

void cls_video::video_main_loop()
{
    while (video_running)
    {
        video_v4l2->read_frame(&img_org);
        video_osd->add_osd(&img_osd, &img_org);
        video_mpp->encode_image(&img_osd);
    }
}

void cls_video::video_loop_start()
{
    video_running = true;

    video_v4l2 = new cls_video_v4l2(this);
    video_mpp = new cls_video_mpp(this);
    video_osd = new cls_video_osd(this);

    main_loop_thread = std::make_unique<std::thread>([this]()
                                                     {
                                                         video_main_loop(); // 直接调用非静态成员函数
                                                     });
}

void cls_video::video_loop_stop()
{
    video_running = false;

    if (main_loop_thread && main_loop_thread->joinable())
    {
        main_loop_thread->join();
    }
    delete video_mpp;
    video_mpp = nullptr;
    delete video_v4l2;
    video_v4l2 = nullptr;
    delete video_osd;
    video_osd = nullptr;
}

void cls_video::init_images()
{
    img_org.width = cfg_cur->video_iw;
    img_org.height = cfg_cur->video_ih;
    img_org.size = img_org.width * img_org.height * 2; // yuv422
    img_org.data = (u_char *)malloc(img_org.size * sizeof(u_char));

    img_osd.width = img_org.width;
    img_osd.height = img_org.height;
    img_osd.size = img_org.size;
    img_osd.data = (u_char *)malloc(img_osd.size * sizeof(u_char));
}

void cls_video::free_images()
{
    if(img_org.data)
    {
        free(img_org.data);
    }
    if(img_osd.data)
    {
        free(img_osd.data);
    }
}
